package com.executor.gateway.core.util;

import com.google.common.base.Strings;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @Auther: miaoguoxin
 * @Date: 2018/12/9 21:16
 * @Description:
 */
public class CommonUtils {
    /**
     * 将url转换成多匹配
     *
     * @param url
     * @return
     */
    public static String convertUrlForMatchingAll(String url) {
        if (!Strings.isNullOrEmpty(url) && url.contains("/")) {
            return url.substring(0, url.lastIndexOf("/")).concat("/*");
        } else {
            return "/*";
        }
    }
    /**
     *
     * 功能描述:获取请求Ip
     *
     * @param:
     * @return:
     * @auther: miaoguoxin
     * @date: 2019/4/30 0030 17:33
     */
    public static String getRemoteIP(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            try {
                ip = request.getRemoteAddress().getAddress().getHostAddress();
            } catch (Exception e) {
                ip = null;
            }
        }
        if (ip != null) {
            //对于通过多个代理的情况，最后IP为客户端真实IP,多个IP按照','分割
            int position = ip.indexOf(",");
            if (position > 0) {
                ip = ip.substring(0, position);
            }
        }
        return ip;
    }
}
